use std::env;
use std::path::Path;
use std::{fs, fs::File};
use std::{io, io::Write};

// 获取文件地址
fn get_file_absolute_path() -> String {
    let root_path = env::current_dir().unwrap();
    let path = Path::new(&root_path).join("storage/2.txt");
    return path.to_str().unwrap().to_string();
}

/**
 * 先进行打开文件，再写内容
 *
 * @param {string} file_path 文件地址
 * @param {string} content 写入的内容
 * @return {io::Result<()>} 返回写入结果
 */
#[allow(dead_code)]
fn write_string_stream(file_path: &str, content: &str) -> io::Result<()> {
    // Opens a file in write-only mode. 如果不存在，则创建
    let mut file = File::create(file_path)?;
    file.write_all(content.as_bytes())?;
    Ok(())
}

// 直接写入
#[allow(dead_code)]
fn write_string(file_path: &str, content: &str) -> io::Result<()> {
    fs::write(file_path, content)?;
    Ok(())
}

// 追加写入
// #[allow(dead_code)]
fn write_string_append(file_path: &str, content: &str) -> io::Result<()> {
    fs::OpenOptions::new()
        .append(true)
        .create(true)
        .open(file_path)?
        .write_all(content.as_bytes())?;
    Ok(())
}

fn main() {
    let path = get_file_absolute_path();
    match write_string_append(&path, "接着写。。。。。。") {
        Ok(_) => println!("写入成功"),
        Err(e) => println!("写入失败, {}", e),
    };
}
